import axios, {
  type AxiosInstance,
  type InternalAxiosRequestConfig,
  type AxiosResponse,
} from 'axios'
import { useUserStore } from '@/stores'
const userStore = useUserStore()
const BASE_URL = import.meta.env.VITE_BASE_API_URL
const request: AxiosInstance = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
})
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.headers['Authorization'] = userStore.token
    //兼容文件上传
    config.headers['Content-Type'] =
      config.data instanceof FormData ? 'multipart/form-data' : 'application/json;charset=utf-8'
    return config
  },
  (err) => {
    window.$message.error('请求失败')
    return Promise.reject(err)
  },
)
request.interceptors.response.use(
  (res: AxiosResponse) => {
    return res.data
  },
  (err) => {
    window.$message.error(err.message)
    return Promise.reject(err)
  },
)


export default request
